package com.meta.pic

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.airbnb.epoxy.CallbackProp
import com.airbnb.epoxy.ModelView
import com.airbnb.epoxy.OnViewRecycled
import kotlin.LazyThreadSafetyMode.NONE

/**
 * 竖直方向的LoadingView
 */
@ModelView(
    autoLayout = ModelView.Size.MATCH_WIDTH_WRAP_HEIGHT, fullSpan = true, saveViewState = true
)
class VerticalLoadingView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
    private val progressBar: ProgressBar by lazy(NONE) {
        findViewById<ProgressBar>(R.id.view_loading_ProgressBar)
    }
    private val textView: TextView by lazy(NONE) {
        findViewById<TextView>(R.id.view_loading_TextView)
    }

    init {
        inflate(context, R.layout.view_vertical_loading, this)
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        val layoutParams = layoutParams
        if (layoutParams is StaggeredGridLayoutManager.LayoutParams) {
            layoutParams.isFullSpan = true
        }
    }

    fun showLoading() {
        progressBar.isVisible = true
        textView.isVisible = false
        isClickable = false
    }

    fun showText(text: String = "") {
        textView.text = text
        progressBar.isVisible = false
        textView.isVisible = true
        isClickable = text.isNotEmpty()
    }

    @CallbackProp
    @JvmOverloads
    fun setOnClickItemListener(listener: View.OnClickListener? = null) {
        setOnClickListener(listener)
    }

    @OnViewRecycled
    fun clear() {
        setOnClickListener(null)
    }
}